import os
import random
import time

from PyQt5.QtWebEngineWidgets import QWebEngineView

from PyQt5.QtWidgets import QWidget, QTableWidgetItem, QHeaderView

from gcz_common.config import config
from PyQt5.QtCore import QTimer, QThread, pyqtSignal, QUrl

from gcz_common.utils.pyqt.ComboCheckBox import ComboCheckBox
from gcz_pyqt.views.home import *

class UIHomeView(QWidget, Ui_Form):
    def __init__(self):
        super(UIHomeView, self).__init__()
        self.setupUi(self)
        self.initParams()
        self.initUI()
        self.initSlot()
        self.initMethod()
        self.initAction()

    def initParams(self):
        self.timer = QTimer()  # 初始化定时器
        self.message = QtWidgets.QMessageBox  # 初始化消息弹框，information消息，critical失败

        self.logCount = 1
        self.lastLog = None
        self.image = None
        self.count = 0
        self.lastTime = time.time()
        self.videoWriter = None

    def btnClick(self, status, title, content):
        if status == self.tmsg.code.info:
            self.message.information(self, title, content)
        elif status == self.tmsg.code.error:
            self.message.critical(self, title, content)
        elif status == self.tmsg.code.warning:
            self.message.warning(self, title, content)

    def initAction(self):
        self.scrapyPBClickCallback = None
        self.clearTablePBClickCallback = None
        self.loadLocalDataPBClickCallback = None

        self.createChartPBClickCallback = None
        self.chartParamsPBClickCallback = None

        self.comboCheckBoxClickCallback = None
    def initUI(self):
        # file = QtCore.QFile(':qss/qss/main.qss')
        # file.open(QtCore.QFile.ReadOnly)
        # styleSheet = file.readAll()
        # styleSheet = str(styleSheet)[1:]
        # self.setStyleSheet(styleSheet)

        self.frame_3.hide()

        self.view = QWebEngineView(self.frame_8)
        self.view.hide()
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(1)
        sizePolicy.setHeightForWidth(self.view.sizePolicy().hasHeightForWidth())
        self.view.setSizePolicy(sizePolicy)
        self.gridLayout_3.addWidget(self.view, 0, 0, 1, 1)

        self.view_3 = QWebEngineView(self.frame_8)
        self.view_3.hide()
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(1)
        sizePolicy.setHeightForWidth(self.view_3.sizePolicy().hasHeightForWidth())
        self.view_3.setSizePolicy(sizePolicy)
        self.gridLayout_4.addWidget(self.view_3, 0, 0, 1, 1)

        self.tableWidget.horizontalHeader().setStyleSheet( "QHeaderView::section{background-color:rgb(155, 194, 230);font:11pt '宋体';color: black;};")
        self.tableWidget.verticalHeader().setStyleSheet( "QHeaderView::section{background-color:rgb(155, 194, 230);font:11pt '宋体';color: black;};")
        self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        self.comboCheckBox = ComboCheckBox(self.comboBox, defaultText="出品地区", callable=lambda :self.comboCheckBoxClick([1, 1], self.comboCheckBox.get()))
        self.comboCheckBox_2 = ComboCheckBox(self.comboBox_2, "上映年份", callable=lambda :self.comboCheckBoxClick([1, 2], self.comboCheckBox_2.get()))
        self.comboCheckBox_3 = ComboCheckBox(self.comboBox_3, "电影种类", callable=lambda :self.comboCheckBoxClick([2, 1], self.comboCheckBox_3.get()))
        self.comboCheckBox_4 = ComboCheckBox(self.comboBox_4, "出品地区", callable=lambda :self.comboCheckBoxClick([2, 2], self.comboCheckBox_4.get()))
        self.comboCheckBox_5 = ComboCheckBox(self.comboBox_5, "上映年份", callable=lambda :self.comboCheckBoxClick([2, 3], self.comboCheckBox_5.get()))
    def initSlot(self):
        self.timer.timeout.connect(self.msgClose)
        self.pushButton_2.clicked.connect(lambda: self.scrapyPBClick(self.pushButton_2.text()))
        self.pushButton_6.clicked.connect(lambda: self.clearTablePBClickPBClick(self.pushButton_6.text()))
        self.pushButton_3.clicked.connect(lambda: self.loadLocalDataPBClick(self.pushButton_3.text()))
        self.pushButton.clicked.connect(lambda: self.openCsvPath(self.pushButton.text()))

    def initMethod(self):
        pass

    # region setUI
    def setUI(self, data):

        self.comboCheckBox.set(data[0])
        self.comboCheckBox_2.set(data[1])
        self.comboCheckBox_3.set(data[2])
        self.comboCheckBox_4.set(data[0])
        self.comboCheckBox_5.set(data[1])

    def setPyEchartUI(self, data):
        # 加载 html 文件并在 pyqt 窗口中显示
        fileUrl = config.file
        if 1 in data:
            pieurl = QUrl(f"file:///{fileUrl.echartPath}{fileUrl.barFileName}.html")
            self.view.load(pieurl)
            self.view.setZoomFactor(0.8)
            self.label.hide()
            self.view.show()

        if 3 in data:
            lineurl = QUrl(f"file:///{fileUrl.echartPath}{fileUrl.pieFileName}.html")
            self.view_3.load(lineurl)
            self.view_3.setZoomFactor(0.8)
            self.label_4.hide()
            self.view_3.show()

    def setTableUI(self, data):
        currentRowCount = self.tableWidget.rowCount()
        self.tableWidget.setRowCount(currentRowCount+1)
        for i in range(0, len(data)):
            self.tableWidget.setItem(currentRowCount, i, QTableWidgetItem(str(data[i])))
        self.tableWidget.scrollToBottom()

        # endregion

    # region Slot
    def openCsvPath(self, btnName):
        self.printLog(f"点击了{btnName}按钮")
        dirs = config.file.csvPath
        if not os.path.exists(dirs):
            os.makedirs(dirs)
        os.startfile(dirs)

    def scrapyPBClick(self, btnName):
        self.printLog(f"点击了{btnName}按钮")
        if (btnName == "开始爬取"):
            titleList = ["影片链接","图片链接","影片中文名","影片外国名","影片评分","评价人数","找到概况","影片的相关内容"]
            self.tableWidget.setColumnCount(len(titleList))
            self.tableWidget.setHorizontalHeaderLabels(titleList)
            self.tableWidget.setStyleSheet("color: rgb(255, 255, 255);\n"
                                           "border: 0px;")
            self.pushButton_2.setText("终止爬取")
            statue = True
        else:
            self.pushButton_2.setText("开始爬取")
            statue = False
        # self.message.information(self, "消息提示", f"点击了{btnName}按钮")
        if self.scrapyPBClickCallback:
            self.scrapyPBClickCallback(statue)

    def clearTablePBClickPBClick(self, btnName):
        self.printLog(f"点击了{btnName}按钮")
        # self.message.information(self, "消息提示", f"点击了{btnName}按钮")
        self.tableWidget.clear()
        self.tableWidget.setColumnCount(0)
        self.tableWidget.setRowCount(0)
        self.tableWidget.setStyleSheet("color: rgb(255, 255, 255);\n"
                                       "border: 0px;\n"
                                       "border-image: url(:/img/img/jpg/bg.jpg);")

        self.label.show()
        self.label_4.show()

        self.view.hide()
        self.view_3.hide()
        if self.clearTablePBClickCallback:
            self.clearTablePBClickCallback()

        self.comboCheckBox.clear()
        self.comboCheckBox_2.clear()
        self.comboCheckBox_3.clear()
        self.comboCheckBox_4.clear()
        self.comboCheckBox_5.clear()

    def loadLocalDataPBClick(self, btnName):
        self.printLog(f"点击了{btnName}按钮")
        # self.message.information(self, "消息提示", f"点击了{btnName}按钮")
        titleList = ["影片链接","图片链接","影片中文名","影片外国名","影片评分","评价人数","找到概况","影片的相关内容"]
        self.tableWidget.setColumnCount(len(titleList))
        self.tableWidget.setHorizontalHeaderLabels(titleList)
        self.tableWidget.setStyleSheet("color: rgb(255, 255, 255);\n"
                                       "border: 0px;")
        if self.loadLocalDataPBClickCallback:
            self.loadLocalDataPBClickCallback()

    def createChartPBClick(self, index, btnName):
        self.printLog(f"点击了{btnName}按钮")
        # self.message.information(self, "消息提示", f"点击了{btnName}按钮")
        if self.createChartPBClickCallback:
            self.createChartPBClickCallback(index)

    def chartParamsPBClick(self, index, value, btnName):
        self.printLog(f"点击了{btnName}按钮")
        # self.message.information(self, "消息提示", f"点击了btnName按钮")
        if self.chartParamsPBClickCallback:
            self.chartParamsPBClickCallback(index, value)

    def comboCheckBoxClick(self, index, data):
        if self.comboCheckBoxClickCallback:
            self.comboCheckBoxClickCallback(index, data)

    # endregion

    def printLog(self, msg):
        if self.lastLog == msg:
            self.logCount = self.logCount + 1
            msg += f' * {self.logCount}'
        else:
            self.logCount = 1
            self.lastLog = msg

        self.label_2.setText(msg)
        self.frame_3.show()
        self.timer.start(2000)
        if config.log.logShow: print(msg)

    def msgClose(self):
        self.frame_3.hide()
        self.timer.stop()
